from google.appengine.api.urlfetch import fetch

import urlparse

# Set Debug = True to display the Response from nirvanix.
debug = False


class Connection:
    # Initialize the connection and set the url when creating the object.
    def __init__(self, base_url):
        self.base_url = base_url
        self.url = urlparse.urlparse(base_url)

    # do a GET request
    def request_get(self, resource, args = None):
        return self.request(resource, "GET", args)

    # do a POST request
    def request_post(self, resource, args = None):
        return self.request(resource, "POST", args)

    # Generic handler for all transactions through the fetch interface.
    def request(self, path, method = "GET", args = None, customheaders = None):
        headers = {}
        # set the headers if they haven't already been passed in.
        if customheaders:
            headers = customheaders
        else:
            headers["User-Agent"] = "Nirvanix Python SDK (App Engine)"
            headers["Content-Length"] = "%d" % len(args)
            headers["Content-Type"] = "application/x-www-form-urlencoded"
                
        # create the URL to be called.
        url = self.base_url + str(path)

        # get the response        
        res = fetch(url, args, method, headers)

        if debug:
            print "Response: ", res.status_code, res.content
            print "headers: ", res.headers
            print res
        return res.content
